package 剑指offer;

public class Offer53_JZ37 {
    public static int search(int[] nums, int target) {
        int leftIndex = leftSearch(nums, target);
        int rightIndex = rightSearch(nums, target);
        if (leftIndex==-1 || rightIndex==-1) {
            return 0;
        }
        System.out.println(leftIndex);
        System.out.println(rightIndex);
        return rightIndex - leftIndex + 1;
    }

    public static int leftSearch(int[] nums, int target) {
        int left = 0, right = nums.length-1;
        while (left <= right) {
            int mid = (left + right) / 2;
            if (target == nums[mid]) {
                right = mid-1;
            } else if (target > nums[mid]) {
                left = mid+1;
            } else if (target < nums[mid]) {
                right = mid-1;
            }
        }
        return (left>=nums.length || nums[left]!=target) ? -1 : left ;
    }

    public static int rightSearch(int[] nums, int target) {
        int left = 0, right = nums.length-1;
        while (left <= right) {
            int mid = (left + right) / 2;
            if (target == nums[mid]) {
                left = mid+1;
            } else if (target > nums[mid]) {
                left = mid+1;
            } else if (target < nums[mid]) {
                right = mid-1;
            }
        }
        return (right<0 || nums[right]!=target) ? -1 : right;
    }

    public static void main(String[] args) {
        int[] arr = {1};
        System.out.println(search(arr, 0));
    }
}
